package com.tiyende.kash.loop.ui.activity

import android.content.Context
import android.content.Intent
import android.view.View
import androidx.core.net.toUri
import androidx.lifecycle.lifecycleScope
import com.tiyende.kash.loop.R
import com.tiyende.kash.loop.TiyendeApp
import com.tiyende.kash.loop.common.CommonActivity
import com.tiyende.kash.loop.databinding.TiyendeActivityScoreBinding
import com.tiyende.kash.loop.databinding.TiyendeActivityScoreIconItemBinding
import com.tiyende.kash.loop.event.TiyendeEventPointHelper
import com.tiyende.kash.loop.event.TiyendeEventPointType
import com.tiyende.kash.loop.sdk.analyse.util.TiyendeReviewUtil
import com.tiyende.kash.loop.utils.log.TiyendeLogger
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import org.json.JSONObject

/**
 * TiyendeCredit
 * @Author wwdeng
 * @CreateTime: 2025/2/6 18:15
 * @Annotation：
 */
class TiyendeScoreActivity: CommonActivity() {
    lateinit var binding: TiyendeActivityScoreBinding

    private val normalIconList = arrayListOf(R.mipmap.tiyende_score1_normal,R.mipmap.tiyende_score2_normal,R.mipmap.tiyende_score3_normal,R.mipmap.tiyende_score4_normal,R.mipmap.tiyende_score5_normal)
    private val selectedIconList = arrayListOf(R.mipmap.tiyende_score1_selected,R.mipmap.tiyende_score2_selected,R.mipmap.tiyende_score3_selected,R.mipmap.tiyende_score4_selected,R.mipmap.tiyende_score5_selected)
    private var scoreIconList = arrayListOf<JSONObject>()
    private var selectStar = -1

    companion object {
        private const val INTENT_KEY_TIPS = "tiyendeScoreTips"
        fun start(context: Context, orderId: String) {
            val intent = Intent(context, TiyendeScoreActivity::class.java)
            intent.putExtra(INTENT_KEY_TIPS, orderId)
            context.startActivity(intent)
        }
    }

    override fun getTiyendeRootView(): View? {
        binding = TiyendeActivityScoreBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initTiyendeView() {
        setTiyendeTitleBarVisibility(View.VISIBLE)
        setTiyendeBackBtnRes(R.mipmap.tiyende_back_white)
        setTiyendeRightBtnRes(R.mipmap.tiyende_customer_white)
        setTiyendeSwitchLangBtnRes(R.mipmap.tiyende_language_icon)
        setTiyendeTextTitleVisibility(View.GONE)
        eventRemark = "Score_Page"
    }

    override fun initTiyendeListener() {
        super.initTiyendeListener()
        binding.btScoreRate.setOnClickListener {
            if (selectStar+1 <= 0){
                return@setOnClickListener
            }
            val startNum = selectStar+1
            TiyendeEventPointHelper.addEventPointRequestAction(TiyendeEventPointType.CLICK.TIYENDE_CLICK_SCORE_RATE,"$startNum")

            /**
             * 数量 >= 4  ->  跳转Google 评分 （AppReviewUtil.launchReviewFlow() ）
             * 数量 < 4   ->  跳转意见反馈  ( UserFeedbackAct )
             */
            if (startNum < 4){
                TiyendeFeedbackActivity.start(this,startNum.toString())
                finish()
            } else {
                TiyendeReviewUtil.launchReviewFlow(this, completed = {
                    TiyendeLogger.e(">>>>>completed>>>>>>>>>>$it")
                    if (!it){
                        //跳转到应用市场
                        onStartGoogleMarket()
                    }
                })
            }
        }
        binding.btScoreNotNow.setOnClickListener {
            TiyendeEventPointHelper.addEventPointRequestAction(TiyendeEventPointType.CLICK.TIYENDE_CLICK_SCORE_NOT_NOW)
            finish()
        }
    }

    override fun loadTiyendeData() {
        binding.txtScoreTips.text = getTiyendeScoreTips()
        scoreIconList.clear()
        for (i in 0..<normalIconList.size){
            val item = JSONObject()
            item.put("iconNormal",normalIconList[i])
            item.put("iconSelected",selectedIconList[i])
            scoreIconList.add(item)
        }
        showTiyendeScoreIconListViews()
    }

    /**
     * 获取订单id
     */
    private fun getTiyendeScoreTips(): String{
        if (intent.extras == null){
            return getString(R.string.tiyende_score_page_tips)
        }
        return intent.extras?.getString(INTENT_KEY_TIPS,getString(R.string.tiyende_score_page_tips)).toString()
    }

    /**
     * 设置评分
     */
    private fun showTiyendeScoreIconListViews(){
        binding.scoreIconLayout.removeAllViews()
        for (i in 0..<scoreIconList.size){
            val item = scoreIconList[i]
            val itemBinding = TiyendeActivityScoreIconItemBinding.inflate(layoutInflater)
            if (i == selectStar){
                itemBinding.imageScoreIcon.setImageResource(item.optInt("iconSelected"))
                itemBinding.imageIndicatorTop.visibility = View.VISIBLE
                itemBinding.imageIndicatorBottom.visibility = View.VISIBLE
            } else {
                itemBinding.imageScoreIcon.setImageResource(item.optInt("iconNormal"))
                itemBinding.imageIndicatorTop.visibility = View.INVISIBLE
                itemBinding.imageIndicatorBottom.visibility = View.INVISIBLE
            }
            itemBinding.imageScoreIcon.setOnClickListener {
                if (selectStar == i){
                    return@setOnClickListener
                }
                selectStar = i
                TiyendeEventPointHelper.addEventPointRequestAction(TiyendeEventPointType.CLICK.TIYENDE_CLICK_SCORE_STAR,(selectStar+1).toString())
                showTiyendeScoreIconListViews()
            }
            binding.scoreIconLayout.addView(itemBinding.root)
        }
    }

    /**
     * 跳转到应用商店
     */
    private fun onStartGoogleMarket(){
        val intent = Intent(Intent.ACTION_VIEW)
        intent.data = "https://play.google.com/store/apps/details?id=${TiyendeApp.app.packageName}".toUri()
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        startActivity(intent)

        lifecycleScope.launch{
            delay(1000)
            finish()
        }
    }

    override fun onStart() {
        super.onStart()
        addEventPointRequestAction(TiyendeEventPointType.PAGE.TIYENDE_PAGE_SCORE_START)
    }

    override fun onDestroy() {
        super.onDestroy()
        addEventPointRequestAction(TiyendeEventPointType.PAGE.TIYENDE_PAGE_SCORE_END)
    }
}